from django.shortcuts import render
from django.http import HttpResponse, StreamingHttpResponse
import json
import simplejson
from .models import User, Room, CheckPoint
import datetime

# Create your views here.

def index(request):

    return HttpResponse("hello")

'''
    接口：查询用户名是否存在
'''
def searchUser(request):
    if request.method == 'POST':
        # 获取用户数据
        # receiveData = json.loads(request.body.decode())
        # username = receiveData['username']
        username = request.POST.get('username')
        print('searchUser--username:', username)
        usernames = User.objects.filter(userName=username)
        print('searchUser--usernames:', usernames)
        if usernames.count() == 0:
            # 没找到
            result = {
                "code": 0,
                "msg": "尚未注册"
            }
        else:
            # 找到了
            result = {
                "code": 1,
                "msg": ""
            }

        return HttpResponse(json.dumps(result))

'''
    接口：注册
'''
def signUp(request):

    if request.method == 'POST':
        # 获取用户数据
        # receiveData = json.loads(request.body.decode())
        # username = receiveData['username']
        # password = receiveData['password']
        # nickname = receiveData['nickname']
        username = request.POST.get('username')
        password = request.POST.get('password')
        nickname = request.POST.get('nickname')
        print('signUp--username:', username)
        print('signUp--password:', password)
        print('signUp--nickname:', nickname)

        usernames = User.objects.filter(userName=username)

        if usernames.count() == 0:
            # 确定没有注册过，执行注册
            user = User(userName=username, userPassword=password, nickName=nickname, creatTime=datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"),
                              refreshTime=datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"))

            # 保存记录
            user.save()

            # 返回消息
            result = {
                "code": '1',
                'msg': ""
            }
            return HttpResponse(json.dumps(result))
        else:
            # 提示，已注册
            # 返回消息
            result = {
                "code": '0',
                'msg': "已注册"
            }
            return HttpResponse(json.dumps(result))
    else:
        # 提交错误情况下返回消息
        result = {
            "code": "0",
            "msg": "注册失败"
        }
        return HttpResponse(json.dumps(result))

'''
    接口：登录
'''
def signIn(request):

    if request.method == 'POST':
        # 获取用户数据
        # receiveData = json.loads(request.body.decode())
        # print('signIn--receiveData:', receiveData)
        # username = receiveData['username']
        # password = receiveData['password']
        username = request.POST.get('username')
        password = request.POST.get('password')
        print('signIn--username:', username)
        print('signIn--password:', password)

        # 查找用户是否存在
        userInfo = User.objects.filter(userName=username)

        if userInfo.count() != 0:
            # 用户已注册
            userInfo = User.objects.get(userName__iexact=username)
            usname = userInfo.userName
            uspassword = userInfo.userPassword
            usnickname = userInfo.nickName
            print('signIn--usname:', usname)
            print('signIn--uspassword:', uspassword)

            # 判断是否是注册用户
            if password == uspassword:
                # 密码正确
                result = {
                    "code": "1",
                    "msg": "登录成功",
                    "data":{
                        "username": usname,
                        "nickname": usnickname
                    }
                }
                return HttpResponse(json.dumps(result))
            else:
                # 密码错误
                result = {
                    "code": "0",
                    "msg": "密码错误"
                }
                return HttpResponse(json.dumps(result))
        else:
            # 用户未注册
            result = {
                "code": "0",
                "msg": "尚未注册"
            }
            return HttpResponse(json.dumps(result))


'''
    创建房间返回房间号  或者  匹配到房间返回房间号
'''
import random
import string
def createRoom(request):
    # 如果请求方式是 POST 的，则是我们想要的
    if request.method == "POST":
        # 获取用户提交的数据
        username = request.POST.get('username')
        print('createRoom--username:', username)
        # 生成1-100随机数，用于随机调取关卡
        num = random.randint(1, 5)  # num得到随机数
        num = str(num)
        # 先查询Room表有没有数据，如果没有则直接创建，如果有则再查找
        roomList = Room.objects.all()  # 获取room表所有数据
        roomCount = roomList.count()  # 获取room表项目数
        print("createRoom--roomCount:", roomCount)
        if roomCount == 0:
            # 创建房间
            # 用集合交集的方法创建随机房间号
            passwd = set(random.sample(string.ascii_letters + string.digits, 8))
            set1 = set(string.ascii_uppercase).intersection(passwd)
            set2 = set(string.ascii_lowercase).intersection(passwd)
            set3 = set(string.digits).intersection(passwd)
            if set1 and set2 and set3:
                str_passwd = ''.join(passwd) + '\n'  # 要把产生的密码变成字符串，因为前面已经给变成集合了
            print("createRoom--str_passwd:", str_passwd)

            print("创建房间-num:", num)
            # 创建一条房间记录
            room = Room(roomId=str_passwd, aPlayer=username, bPlayer=" ", aPlayerScore=" ", bPlayerScore=" ", endingWinner=" ",
                        roomState="0", chainIndex=num,
                        creatTime=datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"),
                              refreshTime=datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"))
            # 保存到数据库
            room.save()

            # 创建成功,返回结果
            result = {
                "code": "1",
                "msg": "创建成功",
                "data": {
                    "roomid": str_passwd,
                }
            }
            return HttpResponse(json.dumps(result))
        else:
            # 查询是否有空房
            # 查询是否有空房，如果有，则加入，如果没有，则创建
            rooms = Room.objects.filter(roomState="0")  # 获取所有state=0的记录
            if rooms.count() == 0:
                # 创建房间
                # 用集合交集的方法创建随机房间号
                passwd = set(random.sample(string.ascii_letters + string.digits, 8))
                set1 = set(string.ascii_uppercase).intersection(passwd)
                set2 = set(string.ascii_lowercase).intersection(passwd)
                set3 = set(string.digits).intersection(passwd)
                if set1 and set2 and set3:
                    str_passwd = ''.join(passwd) + '\n'  # 要把产生的密码变成字符串，因为前面已经给变成集合了
                print("createRoom--str_passwd:", str_passwd)

                print("创建房间-num:", num)
                # 创建一条房间记录
                room = Room(roomId=str_passwd, aPlayer=username, bPlayer=" ", aPlayerScore=" ", bPlayerScore=" ",
                            endingWinner=" ", chainIndex=num,
                            creatTime=datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"),
                            refreshTime=datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"))
                # 保存到数据库
                room.save()

                # 创建成功,返回结果
                result = {
                    "code": "1",
                    "msg": "创建成功",
                    "data": {
                        "roomid": str_passwd,
                    }
                }
                return HttpResponse(json.dumps(result))

            else:
                # 有空房，则匹配成功，返回房间号
                room = rooms.first()  # 取rooms中的第一个记录
                roomId = room.roomId
                print("createRoom--haveRoom:", roomId)
                # 查找对应的房间，修改记录，保存
                exactRoom = Room.objects.get(roomId__exact=roomId)
                exactRoom.bPlayer = username  # 匹配到后将 b 的用户名加入到表中
                exactRoom.roomState = "1"  # 修改房间状态为 全员在
                exactRoom.save()
                # 从关卡表中读取关卡信息
                index = exactRoom.chainIndex
                print("匹配-num:", index)
                check = CheckPoint.objects.get(chainId__exact=index)
                initState = check.initState  # 得到关卡初始值
                goalState = check.goalState  # 得到关卡目标值
                print("匹配-initState:", initState)
                print("匹配-goalState:", goalState)
                print('createRoom--type(initState):', type(initState))

                # 匹配成功,返回结果
                result = {
                    "code": "2",
                    "msg": "匹配成功",
                    "data":{
                        "roomid": roomId,
                        "init": initState,
                        'goal': goalState
                    }
                }
                return HttpResponse(json.dumps(result))


'''
    房间状态查询
    创建房间者A用来查找是否已经匹配到
'''
def searchRoomState(request):
    # 处理POST请求
    if request.method == 'POST':
        # 接受用户上传的数据
        roomid = request.POST.get("roomid")
        print("searchRoomState--roomId:", roomid)
        exactRoom = Room.objects.get(roomId__exact=roomid)  # 找到 用户 所在的房间，并获取信息
        state = exactRoom.roomState  # 获取该房间的状态
        print("searchRoomState--state", state)
        if state == "0":
            # 还在匹配状态
            result = {
                "code": "1",
                "msg": "查询成功",
                "status": "1"
            }
            # print("searchRoomState--正在匹配-内容:", str(result))
            return HttpResponse(json.dumps(result))
        elif state == "1":
            # 匹配成功状态
            # 从关卡表中读取关卡信息
            index = exactRoom.chainIndex
            check = CheckPoint.objects.get(chainId__exact=index)
            initState = check.initState  # 得到关卡初始值
            goalState = check.goalState  # 得到关卡目标值
            print('searchRoomState--type(initState):', type(initState))
            # 匹配成功,返回数据
            result = {
                "code": "1",
                "msg": "查询成功",
                "status": "2",
                "data":{
                    "init": initState,
                    "goal": goalState
                }
            }
            # print("searchRoomState--匹配成功-内容:", str(result))
            return HttpResponse(json.dumps(result))
        elif state == "2":
            # 比赛结束状态
            result = {
                "code": "1",
                "msg": "查询成功",
                "status": "3"
            }

            # print("searchRoomState--比赛结束-内容:", str(result))
            return HttpResponse(json.dumps(result))

'''
    比赛结果上传
'''
def resultCommit(request):
    # 处理POST请求
    if request.method == 'POST':
        # 接受用户上传的数据
        username = request.POST.get('username')
        print('searchRoomState--username:', username)
        roomid = request.POST.get('roomid')
        print('searchRoomState--roomid:', roomid)
        finishtime = request.POST.get('finishtime')
        print('searchRoomState--finishtime:', finishtime)

        # 找到对应的房间，进行下一步的判断
        exactRoom = Room.objects.get(roomId__exact=roomid)  # 找到对应的房间
        # 判断是用户A还是用户B
        if username == exactRoom.aPlayer:
            # 用户A
            exactRoom.aPlayerScore = finishtime  # 修改A的成绩
            exactRoom.save()  # 保存
            # 查看B是否提交过成绩
            bScore = exactRoom.bPlayerScore
            if bScore != " ":
                # B 已经提交
                # 则比较谁输谁赢
                if finishtime < bScore:
                    # A赢
                    exactRoom.endingWinner = exactRoom.aPlayer
                    msg = "恭喜你已获胜"
                if finishtime > bScore:
                    # B赢
                    exactRoom.endingWinner = exactRoom.bPlayer
                    msg = "恭喜你失败了"
                if finishtime == bScore:
                    # 平
                    exactRoom.endingWinner = "平"
                    msg = "恭喜你打平了"
            else:
                # B 还没提交, 则直接返回A已经获胜
                msg = "恭喜你已获胜"
                exactRoom.roomState = '2'
            exactRoom.save()  # 保存结果

            # 返回结果
            result = {
                "code": "1",
                "msg": msg
            }
            return HttpResponse(json.dumps(result))

        if username == exactRoom.bPlayer:
            # 用户B
            exactRoom.bPlayerScore = finishtime  # 修改A的成绩
            exactRoom.save()  # 保存
            # 查看A是否提交过成绩
            aScore = exactRoom.aPlayerScore
            if aScore != " ":
                # B 已经提交
                # 则比较谁输谁赢
                if finishtime < aScore:
                    # B赢
                    exactRoom.endingWinner = exactRoom.bPlayer
                    msg = "恭喜你已获胜"
                if finishtime > aScore:
                    # A赢
                    exactRoom.endingWinner = exactRoom.aPlayer
                    msg = "恭喜你失败了"
                if finishtime == aScore:
                    # 平
                    exactRoom.endingWinner = "平"
                    msg = "恭喜你打平了"
            else:
                # A 还没提交, 则直接返回B已经获胜
                msg = "恭喜你已获胜"
                exactRoom.roomState = '2'
            exactRoom.save()  # 保存结果
            # 返回结果
            result = {
                "code": "1",
                "msg": msg
            }
            return HttpResponse(json.dumps(result))












